﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace GroceryPriceBook.Extensions
{
	public static class ToSelectListItemsHelper
	{
		/// <summary>
		/// Convert list into SelectListItem
		/// <remarks>http://stackoverflow.com/questions/2389328/how-to-write-generic-ienumerableselectlistitem-extension-method</remarks>
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="items"></param>
		/// <param name="nameSelector"></param>
		/// <param name="valueSelector"></param>
		/// <param name="selected"></param>
		/// <param name="attributeKeyValuePair"></param>
		/// <returns></returns>
		public static IEnumerable<SelectListItem> ToSelectListItems<T>(
			 this IEnumerable<T> items,
			 Func<T, string> nameSelector,
			 Func<T, string> valueSelector,
			 Func<T, bool> selected)
		{
			return items.OrderBy(item => nameSelector(item))
				   .Select(item =>
						   new SelectListItem
						   {
							   Selected = selected(item),
							   Text = nameSelector(item),
							   Value = valueSelector(item)
						   });
		}
	}
}